<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      title="注册 / 登录"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- /导航栏 -->

    <!-- 登录表单 -->
    <!--
     基于 Vant 的表单验证:
     1. 使用 van-form 组件包裹所有的表单项 van-field
     2. 给 van-form 绑定submit事件
        当表单提交时触发
        提示: 只有表单验证通过
     3. 使用 Field 的 rules 属性定义校验规则。
    -->
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      ref="login-form"
      @submit="onLogin"
      @failed="onFailed"
    >
      <van-field
        v-model="user.username"
        icon-prefix="toutiao"
        left-icon="shouji"
        center
        placeholder="请输入用户名"
        name="username"
        :rules="formRules.username"
      />
      <van-field
        v-model="user.password"
        icon-prefix="toutiao"
        left-icon="shouji"
        center
        type="password"
        placeholder="请输入密码"
        name="password"
        :rules="formRules.password"
      />
      <van-field
        v-model="user.phone"
        icon-prefix="toutiao"
        left-icon="shouji"
        center
        placeholder="请输入手机号"
        name="mobile"
        :rules="formRules.phone"
      />
      <van-field
        v-model="user.captcha"
        clearable
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        center
        placeholder="请输入验证码"
        name="captcha"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down
            v-if="isCountDownShow"
            :time="1000 * 60"
            format="ss s"
            @finish="isCountDownShow = false"
          />
          <van-button
            v-else
            class="send-btn"
            size="mini"
            type="button"
            round
            :loading="isSendSmsLoading"
            @click.prevent="onSendSms()"
          >发送验证码
          </van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>登录</van-button>
      </div>
    </van-form>
    <!-- /登录表单 -->
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        phone: '', // 手机号
        captcha: '', // 验证码
        password: '',
        username: '',
        uuid: localStorage.getItem('uuid')
      },
      formRules: {
        username: [
          {
            required: true,
            message: '请填写用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请填写密码'
          }
        ],
        phone: [
          {
            required: true,
            message: '请填写手机'
          },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '请填写验证码'
          },
          {
            pattern: /^\d{4}$/,
            message: '验证码格式错误'
          }
        ]
      },
      isCountDownShow: false, // 控制倒计时和发送按钮的显示状态
      isSendSmsLoading: false // 发送验证码按钮的loading状态
    }
  },
  computed: {},
  watch: {},
  created () {
    const uuid = nanoid()
    localStorage.setItem('uuid', uuid)
  },
  mounted () {
  },
  methods: {
    onLogin () {
      this.$toast.loading({
        message: '加载中...', // 提示文本
        forbidClick: true,
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失
      })
      this.postRequestJson('/sys/vip/login', this.user).then(({ data }) => {
        if (data.code === 200) {
          console.log(data)
          this.$store.commit('setUser', data.data)
          // 将后端返回的用户登录状态(token等数据) 放到 Vuex容器中
          // 登录成功，跳转回原来页面
          this.$toast.success({
            message: '登录成功',
            onClose: () => {
              this.$router.replace('/my')
            }
          })
        }
      })
    },
    onFailed (error) {
      console.log(error)
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message, // 提示消息
          position: 'top'
        })
      }
    },
    onSendSms () {
      // 校验手机号码
      this.$refs['login-form'].validate('mobile')
      // 验证通过，请求发送验证码
      this.isSendSmsLoading = true // 展示按钮的loading状态
      const { phone, uuid } = this.user
      this.postRequestForm('/sys/vip/sms', { phone, uuid }).then(({ data }) => {
        console.log(data)
      })
      // 短信发出去了，隐藏发送按钮, 显示倒计时
      this.isCountDownShow = true
      // 倒计时结束 -> 隐藏倒计时，显示发送按钮 （监视倒计时的 finish 事件处理）
      // 无论发送验证码成功还是失败，最后都要关闭f发送按钮的 loading 状态
      this.isSendSmsLoading = false
    }
  }
}
</script>

<style scoped lang="scss">
.login-container {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;

    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }

  .login-btn-wrap {
    padding: 26px 16px;

    .login-btn {
      background-color: #6db4fb;
      border: none;

      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>
